﻿import urllib

#import webapp2
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import search
import indexing
import recipe

INDEX_NAME = indexing.INDEX_NAME

class MainHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(
	template.render('templates/main.html', {}))


class SearchHandler(webapp.RequestHandler):
  def parseParams(self):
    """Filter the param set to the expected params."""
    params = {
      'query': ''
    }
    for k, v in params.iteritems():
      # Possibly replace default values.
      params[k] = self.request.get(k, v)
    return params

  def post(self):
    params = self.parseParams()
    self.redirect('/search?' + urllib.urlencode(
      dict([k, v.encode('utf-8')] for k, v in params.items())))

  def get(self):
    params = self.parseParams()
    params['wizard'] = self.apply_wizard(params)
    search_response = self.do_search(params)

    autofocus = ''
    if len(params['query']) == 0:
      autofocus = 'autofocus'

    template_values = {
      'query': params['query'],
      'wizard': params['wizard'],
      'autofocus': autofocus,
      'search_response': search_response[0],
      'number_found': str(search_response[1])               
    }
    self.response.out.write(template.render('templates/main.html', template_values))

  def do_search(self, params):
    search_response = []
    try:
      results = search.Index(name=INDEX_NAME).search(params['wizard'])
      for scored_document in results:
        r = recipe.Recipe.from_search_doc(scored_document)
        search_response.append([r.title, r.ingredients, r.main_photo, r.source])
    except search.Error:
      logging.exception('Search failed')
    return (search_response, results.number_found)

  def apply_wizard(self, params):
    return params['query']